      
'use strict';
module.exports = {
	/**
	 * 该函数的功能是执行用户付费数据回传。
	 * 当用户支付完成后，微信支付会发送支付回调给vk-pay云函数，vk-pay处理完充值金豆或充值会员的逻辑后，调用本函数进行数据回传
	 * 
	 * client/user/pub/callback 前端调用的url参数地址
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			out_trade_no,
			total_fee,
			_add_time,
			_add_time_str
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		//把requestId和订单号存到-vktest表，出问题时方便追踪
		let requestid_log = await db.collection('vk-test').add({
			tips: "执行了概率回传函数",
			request_id: event.originalParam.context.requestId,
			out_trade_no: out_trade_no
		})

		//声明各广告平台的参数并给予默认值
		let douyin_percent = 100; //抖音回传比例，默认全部回传
		let douyinMinPrice = 0; //最低回传金额
		let douyinMaxPrice = 99999; //最高回传金额
		let newuser = true; //是否仅回传当日新用户的订单,默认开启
		let firstorder = true; //是否仅回传用户的第一笔订单,默认开启
		let hour_backhaul = 24;

		//使用vk公共函数需现在页面顶部引入VK框架，获取今日0点时间戳
		let {
			todayStart
		} = vk.pubfn.getCommonTime(new Date());

		//======获取充值订单信息开始======
		let temp_info = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).get()
		var orderinfo = temp_info.data[0];
		console.log("订单信息====", orderinfo);
		let clickid = temp_info.data[0].clickid || "";

		if (!clickid || clickid == "NoClickid" || clickid.length < 17) {
			res.tips = "不存在clickid";
			return res;
		}
		//======获取充值订单信息结束======

		//======获取回传比例开始======
		let percent = null
		let tfurlpercent = await db.collection('a_config').where({
			name: "RebackPercent",
			tfid: orderinfo.tfid //添加这条数据的代理商ID
		}).get()

		if (tfurlpercent.data.length != 0) {
			percent = tfurlpercent
		} else {
			percent = await db.collection('a_config').where({
				name: "RebackPercent",
				user_id: orderinfo.invite_code || 0 //添加这条数据的代理商ID
			}).get()
		}

		if (percent.data[0]) {
			console.log("存在代理商比例数据", percent);

			douyin_percent = percent.data[0].douyin || 100; //抖音回传比例
			newuser = percent.data[0].newuser; //是否仅回传当日新用户的订单
			firstorder = percent.data[0].firstorder; //是否仅回传用户的第一笔订单
			douyinMinPrice = percent.data[0].douyinMinPrice || 0; //最低回传金额
			douyinMaxPrice = percent.data[0].douyinMaxPrice || 99999; //最高回传金额

			hour_backhaul = percent.data[0].hour_backhaul || 24;
		} else {
			console.log("不存在代理商比例数据");
		}

		let randomnum = Math.floor(Math.random() * (99 - 0)) + 0; //生成一个0到99的随机数
		//======获取回传比例结束======


		//查询已支付订单数量，如已有一条以上的支付订单，则不回传数据给巨量
		let user_recharge_num = await db.collection('a_recharge').where({
			pay_status: 1,
			user_id: orderinfo.user_id
		}).count()

		//如果未开启【仅回传当日新用户的订单】，就把todayStart置为0，这样user_register_date>todayStart永远成立
		if (newuser) {
			console.log("仅回传今日新用户的充值订单,此处不return,继续执行下面逻辑");
		} else {
			todayStart = 0
			console.log("已把todayStart改为0");
		}

		//多少小时内的用户回传
		// if (!newuser) {
		// 	console.log(`仅回传新用户注册x小时订单`);
		// 	let newsday = new Date().getTime();
		// 	if (newsday > (orderinfo.user_register_date * 1 + 3600000 * hour_backhaul)) {
		// 		return res;
		// 	}
		// }

		//如果开启了仅回传用户首笔订单，当查出的已支付订单大于1时，就可以直接return。
		if (firstorder) {
			console.log("仅回传用户首笔订单");
			if (user_recharge_num.total > 1) {
				console.log("已付费订单数量大于1，直接结束");
				return res;
			}
		}

		if (orderinfo.user_register_date < todayStart) {
			console.log("用户注册时间早于今日0点，不执行回传");
			return res;
		}

		//========抖音回传开始========
		console.log("随机数======", randomnum);
		console.log("代理商回传比例======", douyin_percent);
		if (randomnum < douyin_percent * 1) {
			if (total_fee < douyinMinPrice * 100) {
				addvktest("低价格订单不回传抖音");
				return res;
			}
			if (total_fee > douyinMaxPrice * 100) {
				addvktest("高价格订单不回传抖音");
				return res;
			}
			//调用自定义函数进行抖音回传
			await douyin()
		}


		// 业务逻辑结束-----------------------------------------------------------
		return res;

		//数据库添加回传记录
		async function addlog(platform, result) {

			let add_log = await db.collection('jl_huichuanjilu').add({
				type: "active_pay",
				platform: platform,
				user_id: orderinfo.user_id,
				tfid: orderinfo.tfid || "",
				agent_id: orderinfo.invite_code || 0,
				middleman_id: orderinfo.middleman_id || 0,
				adid: orderinfo.ad_id,
				clickid: clickid,
				money: total_fee,
				result: result,
				out_trade_no: out_trade_no,
				time: data._add_time,
				time_str: data._add_time_str
			})
		}

		//数据库添加回传中断日志
		async function addvktest(tips) {
			let addvktest = await db.collection('vk-test').add({
				tips: tips,
				tiptext:"callback",
				out_trade_no: out_trade_no,
				request_id: event.originalParam.context.requestId,
				total_fee: total_fee,
				_add_time: _add_time,
				_add_time_str: _add_time_str
			})
		}

		async function douyin() {

			// 回传支付事件给巨量
			// 付费回传方式
			let jlurl = "https://ad.toutiao.com/track/activate/?callback=" + clickid +
				"&event_type=2" +
				 "&props=%7b%22pay_amount%22%3a" + total_fee+"%7d"
			let tthuichuan_result = await uniCloud.httpclient.request(jlurl, {
				method: 'GET',
				data: {},
				contentType: 'json',
				dataType: 'json'
			})

			if (tthuichuan_result.data.code == 0 || tthuichuan_result.data.status == 200) {
				// 返回被修改的记录条数
				let num = await vk.baseDao.update({
					dbName: "a_recharge", // 表名
					whereJson: { // 条件
						out_trade_no: out_trade_no
					},
					dataJson: { // 需要修改的数据
						is_backhaul: true //订单是否回传
					}
				});
			}


			// 回传记录入库
			addlog("douyin", tthuichuan_result.data)
		}

	}
}

    